from scapy.all import *
from scapy.all import get_if_list

def parse_packet(packet):
    # 打印捕获的数据包
    if packet.haslayer(TCP):
        tcp_layer = packet[TCP]
        ip_layer = packet[IP]

        # 获取源 IP 和端口
        src_ip = ip_layer.src
        src_port = tcp_layer.sport

        # 获取目标 IP 和端口
        dst_ip = ip_layer.dst
        dst_port = tcp_layer.dport

        # 获取 TCP 标志
        flags = tcp_layer.flags
        flag_names = {
            'F': 'FIN',
            'S': 'SYN',
            'R': 'RST',
            'P': 'PSH',
            'A': 'ACK',
            'U': 'URG',
            'E': 'ECE',
            'C': 'CWR'
        }
        flag_str = ' '.join([flag_names[f] for f in flags])

        # 打印数据包摘要
        print(f"Loopback / IP / TCP {src_ip}:{src_port} > {dst_ip}:{dst_port} {flag_str}")

        # 如果有负载数据，打印负载
        if packet.haslayer(Raw):
            raw_data = packet[Raw].load
            print(f"Raw data: {raw_data}")

        # 如果是 PA (PUSH-ACK) 包，进一步分析
        if 'P' in flags and 'A' in flags:
            print("This is a PUSH-ACK packet with raw data.")
            print(f"Sequence Number: {tcp_layer.seq}")
            print(f"Acknowledgment Number: {tcp_layer.ack}")
            print(f"Window Size: {tcp_layer.window}")
            print(f"Checksum: {tcp_layer.chksum}")
            print("-" * 40)


# 获取所有可用的网络接口
interfaces = get_if_list()
print("Available interfaces:", interfaces)

# 选择要捕获流量的网络接口
interface = "\\Device\\NPF_Loopback"
# 定义过滤条件
filter_str = "tcp port 1102"

print(f'interface {interface}')
print(f'filter_str {filter_str}')
ind = 0
while 1:
    # 开始捕获数据包
    print(f'{ind} 开始捕获数据包...')
    packets = sniff(iface=interface, filter=filter_str, count=5)

    # 打印捕获的数据包
    print(f'{ind} 打印捕获的数据包')
    for packet in packets:
        print(packet.summary())
        # parse_packet(packet)
        packet.show()
    ind += 1



